<template>
  <div class="share-page">
    <div class="page-header">
      <h2>分享管理</h2>
      <el-button type="primary" @click="handleCreateShare">
        创建分享
      </el-button>
    </div>

    <div class="share-content">
      <el-table :data="shareList" v-loading="loading">
        <el-table-column label="分享名称" prop="shareName" />
        <el-table-column label="资源名称" prop="resourceName" />
        <el-table-column label="分享类型" width="100">
          <template #default="{ row }">
            <el-tag :type="(row.shareType || '') === 'file' ? 'primary' : 'success'">
              {{ (row.shareType || '') === 'file' ? '文件' : '文件夹' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="访问级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAccessLevelType(row.accessLevel || '')">
              {{ getAccessLevelText(row.accessLevel || '') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="访问次数" prop="accessCount" width="100" />
        <el-table-column label="下载次数" prop="downloadCount" width="100" />
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="过期时间" prop="expireTime" width="180">
          <template #default="{ row }">
            <span v-if="row.isPermanent">永久有效</span>
            <span v-else-if="row.expireTime">{{ row.expireTime }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="handleCopyLink(row)">
                复制链接
              </el-button>
              <el-button size="small" @click="handleEditShare(row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDeleteShare(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑分享对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑分享"
      width="600px"
      @close="handleEditDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="分享名称" prop="shareName">
          <el-input v-model="editForm.shareName" placeholder="请输入分享名称" />
        </el-form-item>

        <el-form-item label="访问级别" prop="accessLevel">
          <el-radio-group v-model="editForm.accessLevel">
            <el-radio label="public">公开</el-radio>
            <el-radio label="password">密码</el-radio>
            <el-radio label="restricted">受限</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="editForm.accessLevel === 'password'"
          label="分享密码"
          prop="sharePassword"
        >
          <el-input
            v-model="editForm.sharePassword"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="有效期限">
          <el-radio-group v-model="isPermanent">
            <el-radio :label="true">永久有效</el-radio>
            <el-radio :label="false">限时有效</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!isPermanent" label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="editForm.expireTime"
            type="datetime"
            placeholder="选择过期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="权限设置">
          <el-checkbox v-model="editForm.allowDownload">允许下载</el-checkbox>
          <el-checkbox v-model="editForm.allowPreview">允许预览</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { shareApi } from '@/api/cd'
import type { CdShareVo } from '@/types/cd'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const loading = ref(false)
const shareList = ref<CdShareVo[]>([])
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const isPermanent = ref(true)
const currentShare = ref<CdShareVo | null>(null)

const editForm = reactive({
  shareName: '',
  accessLevel: 'public',
  sharePassword: '',
  expireTime: '',
  allowDownload: true,
  allowPreview: true
})

const editFormRules: FormRules = {
  shareName: [
    { required: true, message: '请输入分享名称', trigger: 'blur' }
  ],
  accessLevel: [
    { required: true, message: '请选择访问级别', trigger: 'change' }
  ],
  sharePassword: [
    { required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value, callback) => {
      if (editForm.accessLevel === 'password' && !value) {
        callback(new Error('密码模式下必须设置密码'))
      } else {
        callback()
      }
    }}
  ],
  expireTime: [
    { required: true, message: '请选择过期时间', trigger: 'change', validator: (rule, value, callback) => {
      if (!isPermanent.value && !value) {
        callback(new Error('限时有效必须设置过期时间'))
      } else {
        callback()
      }
    }}
  ]
}

onMounted(() => {
  loadShareList()
})

const loadShareList = async () => {
  loading.value = true
  try {
    const userId = Number(userStore.userId) || 1
    console.log('加载分享列表 - userId:', userId)
    const response = await shareApi.getUserShares(userId)
    shareList.value = response.data || []
    console.log('分享列表:', shareList.value)
  } catch (error) {
    console.error('加载分享列表失败:', error)
    ElMessage.error('加载分享列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreateShare = () => {
  ElMessage.info('创建分享功能待实现')
}

const handleCopyLink = (share: CdShareVo) => {
  // 构建完整的分享链接（去掉#，使用history模式）
  const baseUrl = window.location.origin
  const fullUrl = `${baseUrl}${share.shareUrl}`
  navigator.clipboard.writeText(fullUrl)
  ElMessage.success('分享链接已复制到剪贴板')
}

const handleEditShare = (share: CdShareVo) => {
  currentShare.value = share
  editForm.shareName = share.shareName || ''
  editForm.accessLevel = share.accessLevel || 'public'
  editForm.sharePassword = share.sharePassword || ''
  editForm.allowDownload = share.allowDownload ?? true
  editForm.allowPreview = share.allowPreview ?? true
  isPermanent.value = share.isPermanent ?? true
  editForm.expireTime = share.expireTime || ''
  editDialogVisible.value = true
}

const handleEditDialogClose = () => {
  editFormRef.value?.resetFields()
  currentShare.value = null
}

const handleConfirmEdit = async () => {
  if (!editFormRef.value || !currentShare.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          shareId: currentShare.value.shareId,
          shareName: editForm.shareName,
          sharePassword: editForm.accessLevel === 'password' ? editForm.sharePassword : undefined,
          expireTime: isPermanent.value ? undefined : editForm.expireTime,
          accessLevel: editForm.accessLevel,
          allowDownload: editForm.allowDownload,
          allowPreview: editForm.allowPreview
        }
        
        await shareApi.update(params)
        ElMessage.success('修改成功')
        editDialogVisible.value = false
        loadShareList()
      } catch (error) {
        console.error('修改分享失败:', error)
        ElMessage.error('修改分享失败')
      }
    }
  })
}

const handleDeleteShare = async (share: CdShareVo) => {
  try {
    await ElMessageBox.confirm(`确定要删除分享 "${share.shareName}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await shareApi.delete(share.shareId)
    ElMessage.success('删除成功')
    loadShareList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分享失败:', error)
      ElMessage.error('删除分享失败')
    }
  }
}

const getAccessLevelType = (level: string) => {
  const types = {
    public: 'success',
    password: 'warning',
    restricted: 'danger'
  }
  return types[level as keyof typeof types] || 'info'
}

const getAccessLevelText = (level: string) => {
  const texts = {
    public: '公开',
    password: '密码',
    restricted: '受限'
  }
  return texts[level as keyof typeof texts] || level
}
</script>

<style scoped lang="scss">
.share-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
  }
}

.share-content {
  background: white;
  border-radius: 8px;
  padding: 24px;
}
</style>
